<?php

ignore_user_abort(); // 后台运行
set_time_limit(0); // 取消脚本运行时间的超时上限
echo 'start.';

use DtApp\Curl\Get;
use DtApp\Curl\Post;
use think\facade\Db;
use WebSocket\Client;

require __DIR__ . '/../../vendor/autoload.php';
// 请求数据
$prs = json_encode([
    'action' => 'subscribe',
    'args' => [
        'OrderBook500:18', 'OrderBook500:17', 'Trade:17', 'Trade:18'
    ]
]);

// 服务地址
$url = "wss://swapws.bgex.com/realTime";

// 实例化
$context = stream_context_create();
stream_context_set_option($context, 'ssl', 'verify_peer', false);
stream_context_set_option($context, 'ssl', 'verify_peer_name', false);
$client = new Client($url, [
    'timeout' => 60, // 1 minute time out
    'context' => $context,
    'headers' => [
        'Sec-WebSocket-Protocol' => 'soap',
        'origin' => 'localhost',
    ],
]);

// 发送数据
$client->send($prs);

while (true) {
    try {
        // 接收数据
        $message = $client->receive();
        $message = json_decode($message, true);

        if (isset($message['group'])) {
            $group = $message['group'];

            if ($group != 'System') {
                if (isset($message['data'])) {
                    if ($group == 'OrderBook500:18' || $group == 'OrderBook500:17') {
                        $type = "BTC";
                        if ($group == 'OrderBook500:18') $type = 'ETH';

                        if (isset($message['data'])) {
                            $data = $message['data'];
                            $asks = '';
                            foreach ($data['asks'] as $key => $value) {
                                $asks .= jStr($value);
                                var_dump('asks');
                            }
                            xnotice($asks);
                            $bids = '';
                            foreach ($data['bids'] as $key => $value) {
                                $bids .= jStr($value);
                                var_dump('bids');
                            }
                            xnotice($bids);
                        }
                    }
                }
            }
            $s = date('s', time());
            if ($s == 00 || $s == 30) {
                $client->send(json_encode([
                    'action' => 'ping'
                ]));
                var_dump('ping.');
            }

            $myfile = fopen(__DIR__ . "/wss.json", "w") or die("Unable to open file!");
            $txt = json_encode([
                'status' => 0
            ]);
            fwrite($myfile, $txt);
            fclose($myfile);

            var_dump($group);
        } else {

            $myfile = fopen(__DIR__ . "/wss.json", "w") or die("Unable to open file!");
            $txt = json_encode([
                'status' => 1
            ]);
            fwrite($myfile, $txt);
            fclose($myfile);
        }
    } catch (\WebSocket\ConnectionException $e) {
        // Possibly log errors
        var_dump($e->getMessage());

        $myfile = fopen(__DIR__ . "/wss.json", "w") or die("Unable to open file!");
        $txt = json_encode([
            'status' => 1
        ]);
        fwrite($myfile, $txt);
        fclose($myfile);

//        $command = "bash /www/wwwroot/bgex/app/service/ws.sh > /dev/null &";
//        exec($command, $output);
//        var_dump($output);
    }
}

// 关闭连接
//$client->close();

echo 'end.';

function notice($data, $type, $side)
{
    Db::setConfig([
        // 默认数据连接标识
        'default' => 'mysql',
        // 数据库连接信息
        'connections' => [
            'mysql' => [
                // 数据库类型
                'type' => 'mysql',
                // 主机地址
                'hostname' => '139.159.219.224',
                // 用户名
                'username' => 'dtapp',
                // 数据库名
                'database' => 'dtapp',
                // 数据库密码
                'password' => 'rh8AALkEpzklpOGW',
                // 数据库连接端口
                'hostport' => '3301',
                // 数据库编码默认采用utf8
                'charset' => 'utf8mb4',
                // 数据库表前缀
                'prefix' => '',
                // 数据库调试模式
                'debug' => true,
            ],
        ],
    ]);
    $token = Db::table('think_cache')
        ->where('cache_name', "wx6f53456f42d5d1c9_access_token")
        ->order('id desc')
        ->whereTime('cache_expire', '>', time())
        ->value('cache_value');
    if (empty($token)) {
        $get = new Get();
        $res = $get->http("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6f53456f42d5d1c9&secret=c3f4c3d03ab480c4bf17dc528ed97d0c",
            '', true
        );
        Db::table('think_cache')
            ->insert([
                'cache_name' => "wx6f53456f42d5d1c9_access_token",
                'cache_value' => $res['access_token'],
                'cache_expire' => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", time())) - 6000)
            ]);
        $token = $res['access_token'];
    }
    $created_at = $data['created_at'];
    // 链接
    $post = new Post();
    return [
        'wy' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
            "touser" => "ohWG3s6ywGHvzsGGaOZva-9WcquI",
            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
            "data" => [
                "first" => [
                    "value" => "BG大单提醒",
                    "color" => "#173177"
                ],
                // 名称
                "keyword1" => [
                    "value" => $type,
                    "color" => "#173177"
                ],
                // 价格
                "keyword2" => [
                    "value" => $data['px'],
                    "color" => "#173177"
                ],
                // 方向
                "keyword3" => [
                    "value" => $side,
                    "color" => "#173177"
                ],
                // 数量
                "keyword4" => [
                    "value" => $data['qty'],
                    "color" => "#173177"
                ],
                // 时间
                "keyword5" => [
                    "value" => $created_at,
                    "color" => "#173177"
                ],
//                "remark" => [
//                    "value" => "make_fee：" . $data['make_fee'] .
//                        "\noid：" . $data['oid'] .
//                        "\npx：" . $data['px'] .
//                        "\nqty：" . $data['qty'] .
//                        "\nside：" . $data['side'] .
//                        "\ntake_fee：" . $data['take_fee'] .
//                        "\ntid：" . $data['tid'] .
//                        "\nchange：" . $data['change'],
//                    "color" => "#173177"
//                ]
            ]
        ], true),
//        'lb' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
//            "touser" => "ohWG3s3VESc6sMjPw3AhXLmL4nz4",
//            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
//            "data" => [
//                "first" => [
//                    "value" => "BG大单提醒",
//                    "color" => "#173177"
//                ],
//                // 名称
//                "keyword1" => [
//                    "value" => $type,
//                    "color" => "#173177"
//                ],
//                // 价格
//                "keyword2" => [
//                    "value" => $data['px'],
//                    "color" => "#173177"
//                ],
//                // 方向
//                "keyword3" => [
//                    "value" => $side,
//                    "color" => "#173177"
//                ],
//                // 数量
//                "keyword4" => [
//                    "value" => $data['qty'],
//                    "color" => "#173177"
//                ],
//                // 时间
//                "keyword5" => [
//                    "value" => $created_at,
//                    "color" => "#173177"
//                ],
////                "remark" => [
////                    "value" => "make_fee：" . $data['make_fee'] .
////                        "\noid：" . $data['oid'] .
////                        "\npx：" . $data['px'] .
////                        "\nqty：" . $data['qty'] .
////                        "\nside：" . $data['side'] .
////                        "\ntake_fee：" . $data['take_fee'] .
////                        "\ntid：" . $data['tid'] .
////                        "\nchange：" . $data['change'],
////                    "color" => "#173177"
////                ]
//            ]
//        ], true),
//        'ms' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
//            "touser" => "ohWG3s5xS4MAGSXd6lrJktu5xJw0",
//            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
//            "data" => [
//                "first" => [
//                    "value" => "BG大单提醒",
//                    "color" => "#173177"
//                ],
//                // 名称
//                "keyword1" => [
//                    "value" => $type,
//                    "color" => "#173177"
//                ],
//                // 价格
//                "keyword2" => [
//                    "value" => $data['px'],
//                    "color" => "#173177"
//                ],
//                // 方向
//                "keyword3" => [
//                    "value" => $side,
//                    "color" => "#173177"
//                ],
//                // 数量
//                "keyword4" => [
//                    "value" => $data['qty'],
//                    "color" => "#173177"
//                ],
//                // 时间
//                "keyword5" => [
//                    "value" => $created_at,
//                    "color" => "#173177"
//                ],
////                "remark" => [
////                    "value" => "make_fee：" . $data['make_fee'] .
////                        "\noid：" . $data['oid'] .
////                        "\npx：" . $data['px'] .
////                        "\nqty：" . $data['qty'] .
////                        "\nside：" . $data['side'] .
////                        "\ntake_fee：" . $data['take_fee'] .
////                        "\ntid：" . $data['tid'] .
////                        "\nchange：" . $data['change'],
////                    "color" => "#173177"
////                ]
//            ]
//        ], true),
//        'fc' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
//            "touser" => "ohWG3syYIaUIIZyTaDPt1EroBu6U",
//            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
//            "data" => [
//                "first" => [
//                    "value" => "BG大单提醒",
//                    "color" => "#173177"
//                ],
//                // 名称
//                "keyword1" => [
//                    "value" => $type,
//                    "color" => "#173177"
//                ],
//                // 价格
//                "keyword2" => [
//                    "value" => $data['px'],
//                    "color" => "#173177"
//                ],
//                // 方向
//                "keyword3" => [
//                    "value" => $side,
//                    "color" => "#173177"
//                ],
//                // 数量
//                "keyword4" => [
//                    "value" => $data['qty'],
//                    "color" => "#173177"
//                ],
//                // 时间
//                "keyword5" => [
//                    "value" => $created_at,
//                    "color" => "#173177"
//                ],
////                "remark" => [
////                    "value" => "make_fee：" . $data['make_fee'] .
////                        "\noid：" . $data['oid'] .
////                        "\npx：" . $data['px'] .
////                        "\nqty：" . $data['qty'] .
////                        "\nside：" . $data['side'] .
////                        "\ntake_fee：" . $data['take_fee'] .
////                        "\ntid：" . $data['tid'] .
////                        "\nchange：" . $data['change'],
////                    "color" => "#173177"
////                ]
//            ]
//        ], true),
        'gc' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
            "touser" => "ohWG3s0nB13WYDP20eJcyC-tY6Mo",
            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
            "data" => [
                "first" => [
                    "value" => "BG大单提醒",
                    "color" => "#173177"
                ],
                // 名称
                "keyword1" => [
                    "value" => $type,
                    "color" => "#173177"
                ],
                // 价格
                "keyword2" => [
                    "value" => $data['px'],
                    "color" => "#173177"
                ],
                // 方向
                "keyword3" => [
                    "value" => $side,
                    "color" => "#173177"
                ],
                // 数量
                "keyword4" => [
                    "value" => $data['qty'],
                    "color" => "#173177"
                ],
                // 时间
                "keyword5" => [
                    "value" => $created_at,
                    "color" => "#173177"
                ],
//                "remark" => [
//                    "value" => "make_fee：" . $data['make_fee'] .
//                        "\noid：" . $data['oid'] .
//                        "\npx：" . $data['px'] .
//                        "\nqty：" . $data['qty'] .
//                        "\nside：" . $data['side'] .
//                        "\ntake_fee：" . $data['take_fee'] .
//                        "\ntid：" . $data['tid'] .
//                        "\nchange：" . $data['change'],
//                    "color" => "#173177"
//                ]
            ]
        ], true)
    ];
}

function xnotice($data)
{
    Db::setConfig([
        // 默认数据连接标识
        'default' => 'mysql',
        // 数据库连接信息
        'connections' => [
            'mysql' => [
                // 数据库类型
                'type' => 'mysql',
                // 主机地址
                'hostname' => '139.159.219.224',
                // 用户名
                'username' => 'dtapp',
                // 数据库名
                'database' => 'dtapp',
                // 数据库密码
                'password' => 'rh8AALkEpzklpOGW',
                // 数据库连接端口
                'hostport' => '3301',
                // 数据库编码默认采用utf8
                'charset' => 'utf8mb4',
                // 数据库表前缀
                'prefix' => '',
                // 数据库调试模式
                'debug' => true,
            ],
        ],
    ]);
    $token = Db::table('think_cache')
        ->where('cache_name', "wx6f53456f42d5d1c9_access_token")
        ->order('id desc')
        ->whereTime('cache_expire', '>', time())
        ->value('cache_value');
    if (empty($token)) {
        $get = new Get();
        $res = $get->http("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6f53456f42d5d1c9&secret=c3f4c3d03ab480c4bf17dc528ed97d0c",
            '', true
        );
        Db::table('think_cache')
            ->insert([
                'cache_name' => "wx6f53456f42d5d1c9_access_token",
                'cache_value' => $res['access_token'],
                'cache_expire' => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", time())) - 6000)
            ]);
        $token = $res['access_token'];
    }
    // 链接
    $post = new Post();
    return [
        'wy' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
            "touser" => "ohWG3s6ywGHvzsGGaOZva-9WcquI",
            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
            "data" => [
                "first" => [
                    "value" => "BG挂单提醒",
                    "color" => "#173177"
                ],
                // 名称
                "keyword1" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 价格
                "keyword2" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 方向
                "keyword3" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 数量
                "keyword4" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 时间
                "keyword5" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "remark" => [
                    "value" => $data,
                    "color" => "#173177"
                ]
            ]
        ], true),
        'gc' => $post->http("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}", [
            "touser" => "ohWG3s0nB13WYDP20eJcyC-tY6Mo",
            "template_id" => "VTKj33jtnW9QddTFKHalyq7hFLJ0fbiq-aoXzS4pJsU",
            "data" => [
                "first" => [
                    "value" => "BG挂单提醒",
                    "color" => "#173177"
                ],
                // 名称
                "keyword1" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 价格
                "keyword2" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 方向
                "keyword3" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 数量
                "keyword4" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                // 时间
                "keyword5" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "remark" => [
                    "value" => json_encode($data),
                    "color" => "#173177"
                ]
            ]
        ], true)
    ];
}

function judgeSide($str)
{
    switch ($str) {
        case 1:
            return "买入开多";
        case 3:
            return "买入平多";
        case 4:
            return "卖出平多";
        case 5:
            return "买出开空";
        default:
            return $str;
    }
}

function jStr($data)
{
    return $data['1'] . "--" . $data['2'] . " \n ";
}
